// pages/home/home.js
const app = getApp();
const loc = "/static/images/loc@.png";
const search = "/static/images/search.png";
const nores = "/static/images/nores.png";
const phone_ioc = "/static/images/phone.png";
var funcs = require('../../static/js/func.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone_ioc,
    loc,
    nores,
    search,
    inst_name: "四川新都农信村镇银行有限责任公司大丰支行",
    inst_address: "成都市新都区大丰街道方元路222号附14-17号",
    inst_union: "入股公司：四川新都农信村镇银行有限责任公司",
    inst_stop: "是否有停车场：0000000000",
    inst_latitude: "",
    inst_longitude: "",
    inst_telephone: "电话：028-69005001",
    inst_shophours: "夏季 9:00-16:30    冬季 9:00-16:30",
    inst_mapid: "",
    book_todo: 0,
    book_flag: 0,
    bus_arr: ['存款', '贷款','其他'],
    select_project: '存款', //初始化显示存款
    date_list: ['今天','明天'],
    period_list: [],
    week: ["一","二","三","四","五","六","日"],
    select_period:null,
    select_date: '',
    selected_year: 2024,
    selected_month: 12,
    curr_usedfor:"消费",
    usedfor:["消费","生产经营","其他"],
    curr_usedforbusy:"信用卡", 
    usedforbusy:["惠支付","信用卡","POS","电子银行","其他"],
    liked: false,
    placehname:"请输入您的真实姓名",
    placehphone:"请输入您的手机号",
    placehidcard: "请输入您的身份证号（选填）"
  },
  
  //消费、生产经营、其他
  //其他：惠支付、信用卡、POS、电子银行、其他
  judgeTime:function(){
    let now = new Date();
    // 获取当前时间的小时
    let hour = now.getHours();
    let mini = now.getMinutes();
    console.log("当前时间："+hour+":"+mini)
    if(9<=hour && hour < 18){
      if(hour==17 && mini>30){
        this.setData({
          open_flag: false
        })
      }else{
        this.setData({
          open_flag: true
        })
      }
    }else{
        this.setData({
          open_flag: false
        })
      }
  },
  select_usedfor_func:function(e){
    console.log('picker发送选择改变，携带值为', e.detail.value);
    let index = Number(e.detail.value)
    this.setData({
      curr_usedfor: this.data.usedfor[index]
    })
  },
  select_usedforbusi_func:function(e){
    console.log('picker发送选择改变，携带值为', e.detail.value);
    let index = Number(e.detail.value)
    this.setData({
      curr_usedforbusy: this.data.usedforbusy[index]
    })
  },
  select_date_func: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    let result = e.detail.value.split('-');
    console.log(result)
    let year = Number(result[0]);
    let month = Number(result[1]);
    this.setData({
      select_date:e.detail.value,
      selected_year: year,
      selected_month: month
    })

    let _this = this;
    funcs.getAllDays4Month(year,month).then(res => {
      let result = res.data.data;
      console.log(result)
      _this.setData({
        period_list: result
      })
    })
  },  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    console.log("加载onload")
    let openid = app.globalData.openid
    funcs.getMyInfo(openid).then(res=>{
      if(res.data.succeed){
        console.log(res.data.data)
        that.setData({
          uname:res.data.data.uname,
          phone:res.data.data.telnum,
          gender:res.data.data.gender,
          idcard:res.data.data.idcard,
          city:res.data.data.city==null? "无":res.data.data.city,
          area:res.data.data.area==null? "无":res.data.data.area,
          placehname: res.data.data.uname=="匿名用户"? this.data.placehname:res.data.data.uname,
          placehphone: res.data.data.telnum,
          placehidcard:res.data.data.idcard==null||res.data.data.idcard==""? this.data.placehidcard:res.data.data.idcard
        })
        if(res.data.data.uname!=null&&res.data.data.uname!="匿名用户"){
          that.setData({
            inputname:res.data.data.uname
          })
        }else{
          that.setData({
            placehname:"请输入您的真实姓名",
          })
        }
        if(res.data.data.telnum!=null&&this.vertifyPhone(res.data.data.telnum) == 1){
          that.setData({
            inputtelnum:res.data.data.telnum
          })
        }else{
          that.setData({
            placehphone:"请输入您的手机号",
          })
        }
        if(res.data.data.idcard!=null&&this.isValidID(res.data.data.idcard+"")){
          that.setData({
            inputidcard:res.data.data.idcard
          })
        }else{
          that.setData({
            placehidcard: "请输入您的身份证号（选填）"
          })
        }    
      }
    })
    wx.showLoading({
      title: '加载中'
    })
    this.judgeTime()
    // console.log(options);
    var params = decodeURIComponent(options.params);
    var data = JSON.parse(params);
    console.log("跳转后收到的值：")
    console.log(data)
    
    const now = new Date();
    // 获取当前年份
    const year = now.getFullYear();
    // 获取当前月份（需要加1，因为getMonth返回的月份是从0开始计数的）
    const month = now.getMonth() + 1;

    this.setData({
      curr_name: data.name,
      inst_distance: data.distance,
      select_date: year+"-"+month,
      selected_year: year,
      selected_month: month
    })
    
    let _this = this;
    funcs.getInstDatabyInstName(data.name).then(res => {
      let result = res.data.data[0];
      console.log(result)
      let mapid = result.map_id
      let openid = app.globalData.openid
      funcs.judgeFavor(mapid,openid).then(res=>{
        console.log("judge>",res.data)
        if(res.data.succeed){
          _this.setData({
            liked: true
          })
        }else{
          _this.setData({
            liked: false
          })
        }
        _this.setData({
          inst_name: result.name,
          inst_address: result.address,
          inst_union: result.county_union_name,
          inst_stop: result.is_stop=="0000000000"?"无":"有",
          inst_latitude: result.latitude,
          inst_longitude: result.longitude,
          inst_telephone: result.telephone,
          inst_shophours: result.shophours,
          inst_mapid: result.map_id,
          inst_cityname: result.city_name
        })
      })
    }).then(res => {
      setTimeout(function () {
        wx.hideLoading()
      }, 500)
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  errorNotice:function(res){
    wx.showToast({
        title: "因数据安全考虑\r\n目前暂不开放该功能",
        icon: 'none',
        duration: 2000
      })
  },
  clickLikeTap:function(e){
    let that = this
    let openid = app.globalData.openid
    funcs.adToFavor(this.data.inst_mapid,openid).then(res=>{
      if(res.data.succeed){
        if(res.data.data=="添加收藏成功"){
          that.setData({
            liked:true
          })
          wx.showToast({
            title: "添加关注成功",
            icon: 'none',
            duration: 2000
          })
        }else{
          that.setData({
            liked:false
          })
          wx.showToast({
            title: "取消关注成功",
            icon: 'none',
            duration: 2000
          })
        }
      }else{
        wx.showToast({
          title: "请先登录",
          icon: 'error',
          duration: 2000
        })
        // wx.reLaunch({
        //   url: '/pages/my/my',
        // })
      }
    })
  
  },
  closeMask:function(){
    this.setData({
      book_todo: 0,
      book_flag : 0
    })
  },
  todobook:function(res){
    let cityName = this.data.inst_cityname;
    if (!cityName.includes("广元")) {
      wx.showToast({
        title: "因数据安全考虑\r\n暂只开放广元地区预约",
        icon: 'none',
        duration: 4000
      })
      console.log("权限禁止")
      return;
    }
    if(!app.globalData.loginFlag){
      console.log("用户未登录，请先登录")
      wx.showToast({
        title: '用户未登录',
        icon: 'error'
      })
      return
    }
    let _this = this;
    const now = new Date();
    // 获取当前年份
    const year = now.getFullYear();
    // 获取当前月份（需要加1，因为getMonth返回的月份是从0开始计数的）
    const month = now.getMonth() + 1;
    funcs.getAllDays4Month(year,month).then(res => {
      let result = res.data.data;
      console.log(result)
      _this.setData({
        period_list: result
      })
    })
  
    console.log("触发预约开始")
    this.setData({
      book_todo: 1
    })
  },

  submitbook:function(res){
    console.log("触发提交开始")
    
    console.log("提交机构map号信息确认："+this.data.inst_mapid)
    console.log("提交年信息确认："+this.data.selected_year)
    console.log("提交月信息确认："+this.data.selected_month)
    console.log("提交日信息确认："+this.data.select_period)
    let year = this.data.selected_year;
    let month = this.data.selected_month;
    let day = this.data.select_period;
    let map_id = this.data.inst_mapid;

    console.log("提交人姓名信息确认："+this.data.inputname)
    console.log("提交人手机号信息确认："+this.data.inputtelnum)
    console.log("提交人身份证信息确认："+this.data.inputidcard)
    let idcard = this.data.inputidcard;
    let uname = this.data.inputname;
    let telnum = this.data.inputtelnum;

    console.log("提交的业务类别信息确认："+this.data.select_project)
    console.log("提交的金额信息确认："+this.data.inputamount)
    let amount = this.data.inputamount;
    let btype = this.data.select_project;
    let bdesc;
    if(this.data.select_project=="贷款"){
      bdesc = this.data.curr_usedfor;
      // console.log("提交的备注信息确认："+this.data.curr_usedfor)
    }else if(this.data.select_project=="其他"){
      bdesc = this.data.curr_usedforbusy;
      amount = 0.0
      // console.log("提交的备注信息确认："+this.data.curr_usedforbusy)
    }else{
      bdesc = "无";
      // console.log("提交的备注信息确认："+"无")
    }
    console.log("提交的备注信息确认："+bdesc)

    let uid = app.globalData.openid  //用户openid作为唯一标识暂时

        // 验手机正则
        if (this.vertifyPhone(telnum) == 0) {
          wx.showToast({
            title: '手机号格式错误',
            icon: 'error'
          })
          return;
        }
        // console.log("length>"+(idcard+"").length)
        // console.log(idcard+"")
        if((idcard+"")=="undefined"||(idcard+"")==""){

        }else if(!this.isValidID(idcard+"")){
          wx.showToast({
            title: '身份证格式错误',
            icon: 'error'
          })
          return;
        }
        if(day==null){
          wx.showToast({
            title: '请选择日期',
            icon: 'error'
          })
          return;
        }
        if(!this.validateName(uname)){
          wx.showToast({
            title: '姓名格式错误',
            icon: 'error'
          })
          return;
        }
        if((amount+"")=="undefined"||(amount+"").length==0){
          amount = 0.0
        }else if(!this.isDecimal(amount)){
          wx.showToast({
            title: '金额格式错误',
            icon: 'error'
          })
          return;
        }
    funcs.submitbook(uid, idcard,uname,telnum,amount,
      btype,bdesc,year,month,day,map_id).then(res => {
        console.log(res.data)
    })

    this.setData({
      book_todo: 0,
      book_flag : 1
    })
  },
  amountInput:function(e){
    let onInput = e.detail.value
    console.log(e.detail.value)
    this.setData({
      inputamount:onInput
    })
  },
  nameInput:function(e){
    let onInput = e.detail.value
    console.log(e.detail.value)
    this.setData({
      inputname:onInput
    })
  },
  telnumInput:function(e){
    let onInput = e.detail.value
    console.log(e.detail.value)
    this.setData({
      inputtelnum:onInput
    })
  },
  idcardInput:function(e){
    let onInput = e.detail.value
    console.log(e.detail.value)
    this.setData({
      inputidcard:onInput
    })
  },
  bookSuccess:function(res){
    console.log("触发预约成功确认")
    this.setData({
      book_todo: 0,
      book_flag : 0
    })
  },

  select_project_button: function (e) {
    let project = e.currentTarget.dataset.project;
    console.log("选中项目：" + project)
    this.setData({
      select_project: project,
      inputamount: 0.0
    })
  },
  // 手机号格式验证
  vertifyPhone: function (phone) {
    if (!/^1[3456789]\d{9}$/.test(phone)) {
      // 手机号格式不正确，提示用户
      wx.showToast({
        title: '手机格式错误',
        icon: 'error'
      });
      return 0;
    }
    return 1;
  },

  isValidID:function(id) {
    if (id.length !== 18) {
      return false;
    }
    const weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    let sum = 0;
    for (let i = 0; i < 17; i++) {
      sum += parseInt(id[i]) * weight[i];
    }
    const index = sum % 11;
    if (checkCode[index] !== id[17].toUpperCase()) {
      return false;
    }
    return true;
  },
  validateName:function (name) {
    // const regex = /^[a-zA-Z\u4e00-\u9fa5]+( [a-zA-Z\u4e00-\u9fa5]+)*$/;
    // return regex.test(name);
    // 收货人姓名校验(准则:姓名为2-4汉字)

      var regu = /^[\u4E00-\u9FA5]{2,4}$/;
      var re = new RegExp(regu);
      if (!re.test(name)) {
        return false;
      }
      return true;
  },
  isDecimal: function (input) {
    return /^\d+(\.\d+)?$/.test(input); // 正则表达式检查小数
  },
  select_date: function (e) {
    let select_date = e.currentTarget.dataset.date;
    let select_date_day_opened = e.currentTarget.dataset.day_opened;
    //再次查询预约详情
    this.listPeriod(select_date);
    this.setData({
      select_date: select_date,
      select_period: null,
      day_opened: select_date_day_opened
    })
  },

  
  /**
   * 选择预约时段
   * @param {*} e 
   */
  select_period: function (e) {
    console.log(e.currentTarget.dataset)
    let selectedDay = e.currentTarget.dataset.selectedday

    let isafter = e.currentTarget.dataset.isafter; //是否限制
    let display = e.currentTarget.dataset.display;

    if (display==0) {
      console.log("日期无法选择，不予展示")
      return;
    }

    if (isafter==0) {
      console.log("日期无法选择，已过时")
      return;
    }

    // if (full && this.data.isVip == 0) {
    //   return;
    // }
    // console.log(this.data.day_opened)
    // if (this.data.day_opened == false) {
    //   return;
    // }
    console.log(selectedDay)
    this.setData({
      select_period: selectedDay,
    })
    console.log(this.data.select_period)
  },
  
  jumptomap: function(res){
    // console.log("here")
    // console.log(res.currentTarget.dataset)
    let data = res.currentTarget.dataset

    let longitude = data.longitude;
    let latitude = data.latitude;
    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    let x = longitude - 0.0065;
    let y = latitude - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    let wz = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    let lon = z * Math.cos(wz);
    let lat = z * Math.sin(wz);
    longitude=lon;
    latitude=lat;
    console.log(latitude+latitude+data.nam+data.address)
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: data.name,
      address: data.address
    })
  },
  call_phone: function (res) {
    let data = res.currentTarget.dataset
    wx.showModal({
      title: "提示",
      content: "拨打 "+data.telephone+" ?",
      complete: (res) => {
        if (res.cancel) {
          return
        }
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: data.telephone,
            success: function () {
              console.log("拨打电话成功！")
            },
            fail: function () {
              console.log("拨打电话失败！")
            }
          })
        }
      }
    })
  }
})